package com.lewis.module.m2.api.bill.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lewis.common.core.entity.BaseResult;
import com.lewis.common.core.entity.controller.BaseController;
import com.lewis.common.core.entity.page.PageResult;
import com.lewis.common.core.utils.StringUtil;
import com.lewis.module.m2.api.bill.code.entity.BillCode;
import com.lewis.module.m2.api.bill.code.service.IBillCodeService;
import com.lewis.module.m2.api.bill.entity.Bill;
import com.lewis.module.m2.api.bill.service.IBillService;
import com.lewis.module.m2.api.bill.vo.BillDeleteVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * billController
 *
 * @author lewis
 * @since 2021-11-02
 */
@Api(tags = "账单")
@Slf4j
@RestController
@RequestMapping("/bill")
public class BillController extends BaseController {

	@Resource
	private IBillService billService;

	@Resource
	private IBillCodeService billCodeService;

	/**
	 * 查询bill列表
	 */
	@GetMapping("/listLewis")
	public BaseResult listLewis(Bill bill) {
		StringBuilder msg = new StringBuilder();
		List<Bill> billList = getBillList(bill, msg);
		for (int i = 0; i < billList.size(); i++) {
			// 只收纳100个数据
			if (i == 100) {
				break;
			}
			Bill bill1 = billList.get(i);
			String type = bill1.getBillType() == 1 ? "收入" : "支出";
			// id 类型 金额 备注 时间
			msg.append(bill1.getId()).append(" ").append(type).append(" ").append(bill1.getMoney()).append(" ").append(bill1.getRemark()).append(" ").append(DateFormatUtils.format(bill1.getCtime(), "yyyy-MM-dd HH:mm:ss")).append("\n");
		}
		return BaseResult.ok().setData(msg);
	}

	/**
	 * 查询余额
	 */
	@GetMapping("/getBalance")
	public BaseResult getBalance(Bill bill) {
		StringBuilder msg = new StringBuilder();
		getBillList(bill, msg);
		return BaseResult.ok().setData(msg);
	}

	private List<Bill> getBillList(Bill bill, StringBuilder msg) {
		List<Bill> billList = billService.list(
				new LambdaQueryWrapper<Bill>()
						.eq(StringUtil.isNotNull(bill.getBillType()), Bill::getBillType, bill.getBillType())
						.eq(StringUtil.isNotNull(bill.getUserId()), Bill::getUserId, bill.getUserId())
						.eq(StringUtil.isNotNull(bill.getId()), Bill::getId, bill.getId())
						.like(StringUtil.isNotNull(bill.getRemark()), Bill::getRemark, bill.getRemark())
						.eq(StringUtil.isNotNull(bill.getBillCodeId()), Bill::getBillCodeId, bill.getBillCodeId())
						.le(StringUtil.isNotNull(bill.getCtime()), Bill::getCtime, bill.getCtime())
						.orderByDesc(Bill::getId)
		);

		BigDecimal incomeAll = new BigDecimal(0);
		BigDecimal payAll = new BigDecimal(0);

		for (Bill bill1 : billList) {
			if (bill1.getBillType() == 1) {
				incomeAll = incomeAll.add(new BigDecimal(Double.toString(bill1.getMoney())));
			} else if(bill1.getBillType() == 0) {
				payAll = payAll.add(new BigDecimal(Double.toString(bill1.getMoney())));
			}
		}

		msg.append("总收入：").append(incomeAll).append("\n");
		msg.append("总支出：").append(payAll).append("\n");
		msg.append("总余额：").append(incomeAll.subtract(payAll)).append("\n");

		return billList;
	}

	/**
	 * 新增bill
	 */
	@PostMapping("/addLewis")
	public BaseResult addLewis(@RequestBody Bill bill) {

		// 确保该用户有该账单
		BillCode one = billCodeService.getOne(
				new LambdaQueryWrapper<BillCode>()
						.eq(BillCode::getId, bill.getBillCodeId())
						.eq(BillCode::getUserId, bill.getUserId())
		);

		if (one == null) {
			return BaseResult.fail().setMsg("名下无此账单");
		}

		StringBuilder msg = new StringBuilder();

		if (!billService.save(bill)) {
			return BaseResult.fail().setMsg("记账失败");
		}

		msg.append("记账完毕，要保持记账的好习惯哦~\n");

		// 账单余额
		List<Bill> billList = billService.list(
				new LambdaQueryWrapper<Bill>()
						.eq(StringUtil.isNotNull(bill.getUserId()), Bill::getUserId, bill.getUserId())
						.eq(StringUtil.isNotNull(bill.getBillCodeId()), Bill::getBillCodeId, bill.getBillCodeId())
		);

		BigDecimal incomeAll = new BigDecimal(0);
		BigDecimal payAll = new BigDecimal(0);

		for (Bill bill1 : billList) {
			if (bill1.getBillType() == 1) {
				incomeAll = incomeAll.add(new BigDecimal(Double.toString(bill1.getMoney())));
			} else {
				payAll = payAll.add(new BigDecimal(Double.toString(bill1.getMoney())));
			}
		}

		msg.append("[ ").append(one.getBillName()).append(" ] 总余额：").append(incomeAll.subtract(payAll)).append("\n");

		return BaseResult.ok().setData(msg);
	}

	/**
	 * 删除明细
	 */
	@PostMapping("/delete")
	public BaseResult delete(@RequestBody BillDeleteVo billDeleteVo) {

		StringBuilder msg = new StringBuilder();
		Integer userId = billDeleteVo.getUserId();
		Long id = billDeleteVo.getId();
		LambdaQueryWrapper<Bill> billLambdaQueryWrapper = new LambdaQueryWrapper<>();
		billLambdaQueryWrapper.eq(Bill::getUserId, userId);
		billLambdaQueryWrapper.eq(Bill::getId, id);
		Bill bill = billService.getOne(billLambdaQueryWrapper);

		if (bill == null) {
			return BaseResult.fail().setMsg("禁止删除其他人的明细");
		}

		if (billService.remove(billLambdaQueryWrapper)) {
			msg.append("删除明细完毕，要保持记账的好习惯哦~\n");

			// 账单余额
			List<Bill> billList = billService.list(
					new LambdaQueryWrapper<Bill>()
							.eq(StringUtil.isNotNull(billDeleteVo.getUserId()), Bill::getUserId, billDeleteVo.getUserId())
							.eq(StringUtil.isNotNull(billDeleteVo.getBillCode()), Bill::getBillCodeId, billDeleteVo.getBillCode())
			);

			BigDecimal incomeAll = new BigDecimal(0);
			BigDecimal payAll = new BigDecimal(0);

			for (Bill bill1 : billList) {
				if (bill1.getBillType() == 1) {
					incomeAll = incomeAll.add(new BigDecimal(Double.toString(bill1.getMoney())));
				} else {
					payAll = payAll.add(new BigDecimal(Double.toString(bill1.getMoney())));
				}
			}

			BillCode one = billCodeService.getOne(
					new LambdaQueryWrapper<BillCode>().eq(BillCode::getId, bill.getBillCodeId())
			);

			msg.append("[").append(one.getBillName()).append("] 总余额：").append(incomeAll.subtract(payAll));

			return BaseResult.ok().setData(msg);
		}
		return BaseResult.fail().setMsg("删除失败");
	}

	@ApiOperation(value = "查询账单明细列表", notes = "")
	@GetMapping("/list")
	public PageResult list(Bill bill) {
		return billService.getBillList(bill);
	}

	@ApiOperation(value = "获取账单明细详细信息", notes = "")
	@GetMapping(value = "/{id}")
	public BaseResult getInfo(@PathVariable("id") Long id) {
		return ok().setData(billService.getById(id));
	}

	@ApiOperation(value = "新增账单明细", notes = "")
	@PostMapping
	public BaseResult add(@RequestBody Bill bill) {
		return getResult(billService.save(bill));
	}

	@ApiOperation(value = "修改账单明细", notes = "")
	@PutMapping
	public BaseResult edit(@RequestBody Bill bill) {
		return getResult(billService.updateById(bill));
	}

	@ApiOperation(value = "删除账单明细", notes = "")
	@DeleteMapping("/{ids}")
	public BaseResult remove(@PathVariable Long[] ids) {
		return getResult(billService.removeByIds(Arrays.asList(ids)));
	}
}